package kxfang.com.food.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.orhanobut.hawk.Hawk;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import kxfang.com.base.activity.MvvmBaseActivity;
import kxfang.com.base.viewmodel.IMvvmBaseViewModel;
import kxfang.com.common.constant.Constant;
import kxfang.com.common.utils.HawkUtil;
import kxfang.com.common.utils.StatusBarUtil;
import kxfang.com.food.R;
import kxfang.com.food.databinding.FoodActivityFoodWebBinding;

/**
 * Created by WL
 * on 2020/7/17
 * Class Content 美食网页
 */
public class FoodWebActivity extends MvvmBaseActivity<FoodActivityFoodWebBinding, IMvvmBaseViewModel> {
    ;
    private String url;
    WebSettings webSettings;
    public double latitude = 0, longitude = 0;
    String idUrl = "&userid=" + (HawkUtil.getUserId() == null ? 0 : HawkUtil.getUserId());

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewDataBinding.ivBack.setOnClickListener((v) -> {
            finish();
        });

        StatusBarUtil.setTopActivityView(this, viewDataBinding.topView);
        if (HawkUtil.get("lat") != null) {
            latitude = Hawk.get("lat");
            longitude = Hawk.get("lng");
        }
        String today = "/meishicn/todayDeal.html?type=mobile";
        String bigPin = "/meishicn/daPaiMeishi.html?type=mobile";
        String biEat = "/meishicn/eatList.html?type=mobile";
        String temp;
        switch (getIntent().getIntExtra("type", 0)) {
            case 1:
                temp = biEat;
                viewDataBinding.titleText.setText("必吃榜");
                break;
            case 2:
                viewDataBinding.titleText.setText("大牌惠吃");
                temp = bigPin;
                break;
            default:
                viewDataBinding.titleText.setText("今日特价");
                temp = today;
                break;
        }
        url = Constant.LOAD_WEBVIEWURL + temp + "&lat=" + latitude + "&lng=" + longitude;
        if (getIntent().getIntExtra("type", 0) != 1) {
            url = url.concat(idUrl);
        }
        initView(url);
    }

    @Override
    protected IMvvmBaseViewModel getViewModel() {
        return null;
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.food_activity_food_web;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    private void initView(String url) {
        webSettings = viewDataBinding.web.getSettings();
        viewDataBinding.web.clearCache(true);
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        viewDataBinding.web.addJavascriptInterface(new test(FoodWebActivity.this), "test");
        viewDataBinding.web.setWebChromeClient(new WebChromeClient());
        viewDataBinding.web.setWebViewClient(new WebViewClient() {
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //终止加载
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                viewDataBinding.web.loadUrl(url);
                return true;
            }
        });
        viewDataBinding.web.loadUrl(url);
    }

    class test {

        Context context;
        JSONObject jsonObject;

        public test(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void userLogin() {
            Log.e("TAG", "userLogin: ");
            if (HawkUtil.getUserId() == null) {
                //未登录
                //myShowDialog("您还未登录", context);
            }
        }

        @JavascriptInterface
        public void goBuy(String param) {
            //{"RUserID":"2215","StoreID":"20041720441744171357465","list":[{"GoodsId":"20053020442944293460399","Num":1}]}
            //{"RUserID":"615","StoreID":"20041517422542254200902","list":[{"GoodsID":"20042016111311132382232","Num":4}],"IsDel":false}
            //立即下单
            System.out.println(param + "-------------->");
            try {
                jsonObject = new JSONObject(param);
                JSONArray jsonArray = jsonObject.getJSONArray("list");
//                List<PostShopIdModel> data = new ArrayList<>();
//                for (int i = 0; i < jsonArray.length(); i++) {
//                    PostShopIdModel model = new PostShopIdModel();
//                    model.setGoodsID(jsonArray.getJSONObject(i).getString("GoodsId"));
//                    model.setNum(jsonArray.getJSONObject(i).getInt("Num"));
//                    data.add(model);
//                }
                //Navigate.push(FoodWebActivity.this, CreateOrderFragment.class, jsonObject.getString("StoreID"),
                // data, new AddressPack(), false);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @JavascriptInterface
        public void productInfo(String id) {
//            Intent intent = new Intent(context, StoreWebViewActivity.class);
//            id = id.substring(1,id.length()-1);
//            intent.putExtra("id", id);
//            startActivity(intent);
        }

        @JavascriptInterface
        public void storeInfo(String storeId) {
//            Intent intent = new Intent(context, HomeStoreDetailFragment.class);
//            intent.putExtra("id", storeId.substring(1, storeId.length() - 1));
//            startActivity(intent);
        }
    }
}
